<?php

namespace App\Admin\Controllers;

use App\Admin\Filters\TimestampBetween;
use App\Models\Carbarn;
use App\Models\Order;
use App\Http\Controllers\Controller;
use App\Models\Station;
use App\Models\User;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use Encore\Admin\Grid\Filter;

class OrderController extends Controller
{
    use HasResourceActions;

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->header('订单')
            ->description('列表')
            ->body($this->grid());
    }

    /**
     * Show interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header('Detail')
            ->description('description')
            ->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->header('Edit')
            ->description('description')
            ->body($this->form()->edit($id));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header('Create')
            ->description('description')
            ->body($this->form());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Order);
        $grid->model()->with(['station', 'carbarn', 'user'])->orderBy("id", "desc");

        $grid->id('Id');
        $grid->sn('订单号');
        $grid->column('userId','用户ID');
        $grid->column('user.name','用户昵称');
        $grid->addTime('下单时间')->display(function ($item) {
            return $this->addTime->format('Y-m-d H:i:s');
        });
        $grid->type('订单类型')->display(function ($item) {
            return $this->typeText;
        });
        $grid->payStateText('支付状态')->display(function () {
            return sprintf(
                '<span class="label label-%s">%s</span>',
                $this->isPaid() ? "success" : "warning",
                $this->payStateText
            );
        });
        $grid->amount('金额');
        $grid->column('洗车舱')->display(function () {
           return optional($this->carbarn)->name;
        });
        $grid->column('门店')->display(function () {
            return optional($this->station)->name;
        });

        $grid->filter(function (Filter $filters) {
            $filters->column(1/2, function ($filters) {
                $filters->equal('sn', '订单号');
                $filters->equal('user_id', '用户')->select(function ($id) {
                    $user = User::find($id);
                    if ($user) {
                        return [$user->id => sprintf("%s【%s】", $user->name, $user->id)];
                    }
                })->ajax(route('user.json.select'));
                $filters->equal('type', '订单类型')->select(Order::$typeText);
            });

            $filters->column(1/2, function ($filters) {
                $filters->equal('carbarnId', '洗车舱')->select(Carbarn::pluck('name', 'id'));
                $filters->equal('mcstationId', '门店')->select(Station::pluck('name', 'id'));
                $filters->equal('payState', '支付状态')->select(Order::$payStateText);
                $filters->use(new TimestampBetween('addTime', '时间范围'))->datetime();
            });
        });

        $grid->disableActions();
        $grid->disableCreateButton();
        $grid->disableRowSelector();

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Order::findOrFail($id));

        $show->id('Id');
        $show->userId('UserId');
        $show->sn('Sn');
        $show->state('State');
        $show->payState('PayState');
        $show->addTime('AddTime');
        $show->payTime('PayTime');
        $show->paymentId('PaymentId');
        $show->amount('Amount');
        $show->shippingFee('ShippingFee');
        $show->payFee('PayFee');
        $show->resourceAmount('ResourceAmount');
        $show->paymentName('PaymentName');
        $show->confirmTime('ConfirmTime');
        $show->consigneeDesc('ConsigneeDesc');
        $show->shippingId('ShippingId');
        $show->shippingDesc('ShippingDesc');
        $show->shippingState('ShippingState');
        $show->shippingTime('ShippingTime');
        $show->tax('Tax');
        $show->invoiceNo('InvoiceNo');
        $show->isSynToERP('IsSynToERP');
        $show->partnerStoreId('PartnerStoreId');
        $show->masterOrderId('MasterOrderId');
        $show->subOrderCount('SubOrderCount');
        $show->paidAmount('PaidAmount');
        $show->discountAmount('DiscountAmount');
        $show->isCod('IsCod');
        $show->favourActName('FavourActName');
        $show->feedback('Feedback');
        $show->usedGiftCards('UsedGiftCards');
        $show->giftCardsPayDetail('GiftCardsPayDetail');
        $show->giftCardsPayAmount('GiftCardsPayAmount');
        $show->gcardsPaidAmount('GcardsPaidAmount');
        $show->goodsAmount('GoodsAmount');
        $show->invoiceId('InvoiceId');
        $show->balancePaidAmount('BalancePaidAmount');
        $show->washJobId('WashJobId');
        $show->merchantId('MerchantId');
        $show->settleState('SettleState');
        $show->settlementId('SettlementId');
        $show->goodsName('GoodsName');
        $show->goodsTypePin('GoodsTypePin');
        $show->carbarnId('CarbarnId');
        $show->mcstationId('McstationId');

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new Order);

        $form->number('userId', 'UserId');
        $form->text('sn', 'Sn');
        $form->switch('state', 'State');
        $form->switch('payState', 'PayState');
        $form->number('addTime', 'AddTime');
        $form->number('payTime', 'PayTime');
        $form->switch('paymentId', 'PaymentId');
        $form->decimal('amount', 'Amount')->default(0.00);
        $form->decimal('shippingFee', 'ShippingFee')->default(0.00);
        $form->decimal('payFee', 'PayFee')->default(0.00);
        $form->decimal('resourceAmount', 'ResourceAmount')->default(0.00);
        $form->text('paymentName', 'PaymentName');
        $form->number('confirmTime', 'ConfirmTime');
        $form->textarea('consigneeDesc', 'ConsigneeDesc');
        $form->number('shippingId', 'ShippingId');
        $form->textarea('shippingDesc', 'ShippingDesc');
        $form->switch('shippingState', 'ShippingState');
        $form->number('shippingTime', 'ShippingTime');
        $form->decimal('tax', 'Tax')->default(0.00);
        $form->text('invoiceNo', 'InvoiceNo');
        $form->switch('isSynToERP', 'IsSynToERP');
        $form->number('partnerStoreId', 'PartnerStoreId');
        $form->number('masterOrderId', 'MasterOrderId');
        $form->number('subOrderCount', 'SubOrderCount');
        $form->decimal('paidAmount', 'PaidAmount')->default(0.00);
        $form->decimal('discountAmount', 'DiscountAmount')->default(0.00);
        $form->switch('isCod', 'IsCod');
        $form->text('favourActName', 'FavourActName');
        $form->text('feedback', 'Feedback');
        $form->switch('usedGiftCards', 'UsedGiftCards');
        $form->text('giftCardsPayDetail', 'GiftCardsPayDetail');
        $form->decimal('giftCardsPayAmount', 'GiftCardsPayAmount')->default(0.00);
        $form->decimal('gcardsPaidAmount', 'GcardsPaidAmount')->default(0.00);
        $form->decimal('goodsAmount', 'GoodsAmount')->default(0.00);
        $form->number('invoiceId', 'InvoiceId');
        $form->decimal('balancePaidAmount', 'BalancePaidAmount')->default(0.00);
        $form->number('washJobId', 'WashJobId');
        $form->number('merchantId', 'MerchantId');
        $form->number('settleState', 'SettleState');
        $form->number('settlementId', 'SettlementId');
        $form->text('goodsName', 'GoodsName');
        $form->number('goodsTypePin', 'GoodsTypePin');
        $form->number('carbarnId', 'CarbarnId');
        $form->number('mcstationId', 'McstationId');

        return $form;
    }

    public function trendToday()
    {
        $orderCounts = Order::selectRaw("date_format(from_unixtime(addTime), '%H') as hour, count(*) as counts")
            ->where("addTime", ">=", strtotime('today'))
            ->groupBy(\DB::raw("date_format(from_unixtime(addTime), '%H')"))
            ->get()->pluck("counts", "hour")->toArray();
        $data = [];
        for ($i = 0; $i <= 24; $i++)
        {
            $hour = $i;
            $counts = 0;
            if (isset($orderCounts[$i]))
            {
                $counts = $orderCounts[$i];
            }
            $data[] = compact('hour', 'counts');
        }
        return response()->json($data);
    }
}
